<template>
  <div class="secret" id="secret">
    <div class="tips">
      操作说明
      <a-tooltip placement="rightBottom">
        <template #title
          >操作说明:开启分级保护后，管理员创建用户后交由安全员设置用户密级，只有安全员设置好密级后才能启用用户。</template
        >
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <a-tabs v-model:activeKey="tabActive" @change="changeTopTabs">
      <a-tab-pane :key="item.key" :tab="item.tab" v-for="item in paneList"> </a-tab-pane>
    </a-tabs>
    <div class="selectBox">
      <div>
        <span>状态：</span>
        <a-select
          placeholder="请选择"
          class="userSecret"
          v-model:value="params.status"
          :options="statusOptions"
          allow-clear
          @change="onSearch"
        ></a-select>
      </div>
      <div>
        <span>所属组织：</span>

        <a-tree-select
          class="AtreeSelect"
          v-model:value="params.orgId"
          ref="siteDetail_treeSelect"
          show-search
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择"
          allow-clear
          treeNodeFilterProp="name"
          :fieldNames="{
            children: 'children',
            label: 'name',
            value: 'id',
          }"
          tree-default-expand-all
          :tree-data="OrgData"
          @select="onSearch"
        >
        </a-tree-select>
      </div>
      <div v-if="tabActive == 1">
        <span>所属密级：</span>
        <a-select
          placeholder="请选择"
          class="userSecret"
          v-model:value="params.userSecretId"
          :options="userSecretIdOptions"
          @change="onSearch"
          allow-clear
        ></a-select>
      </div>
      <div>
        <a-input
        class="userSecret"
        style="width: 200px;height:31px"
          v-model:value="params.keyWord"
          placeholder="请输入关键字"
          @blur="onSearch"
          @pressEnter="onSearch"
          allow-clear
        >
        <template #suffix>
            <i
              class="iconfont icon-search"
              @click="onSearch"
            ></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable
      :columns="columns_audit"
      :dataSource="configData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="tagBaseTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="configData.total"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column">
            <span>{{ text }}</span>
          </table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'isEnabled'">
          <span v-if="text">启用</span>
          <span v-else style="color: #999">禁用</span>
        </template>

        <template v-if="column.dataIndex === 'userSecretId'">
          <a-select
            :disabled="!btnPerm.includes('securityLevelAble')"
            placeholder="请选择"
            class="userSecret"
            v-model:value="record.userSecretId"
            :options="userSecretIdOptions"
            @change="userSecretBlur(record)"
            allow-clear
          ></a-select>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="auditRecord"
          :disabled="!rowSelection.length || !btnPerm.includes('securityLevelAble')"
          >批量设置密级</a-button
        >
      </template>
    </baseTable>

    <!-- 批量设置密级模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
      class="sensitive_modal"
      :buttons="buttons"
    >
      <template v-slot:body>
        <a-form
          :model="formState"
          autoComplete="off"
          labelAlign="right"
          ref="threeMemberForm"
        >
          <a-form-item
            name="userSecretId"
            label="设置人员密级"
            :rules="[{ required: true, message: '人员密级不可为空！' }]"
          >
            <a-select
              placeholder="请选择"
              class="userSecret"
              v-model:value="formState.userSecretId"
              :options="userSecretIdOptions"
              allow-clear
            ></a-select> </a-form-item
        ></a-form>
      </template>
    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, reactive, nextTick } from "vue";
import request from "@/api/index";
import baseTable from "@/components/table/baseTable.vue";
import columns from "@/components/table/tableConfig/tableColumn/systemTableColumn";
import { useFixeWidth, styleWidth } from "@/hooks/useFixeWidth";
import baseModal from "@/components/modal/baseModal.vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { message, SelectProps } from "ant-design-vue";
import { routerPerm } from "@/utils/common";

// interFace
interface dataSourceType {
  [propName: string]: any;
}
//data
const btnPerm = ref<any[]>([]);
let columns_audit = ref(JSON.parse(JSON.stringify(columns.userSecretColumns)));
const tabActive = ref(0);
const paneList = ref([
  {
    key: 0,
    tab: "待设置",
  },
  {
    key: 1,
    tab: "已设置",
  },
]);
const statusOptions = ref([
  {
    value: 0,
    label: "禁用",
  },
  {
    value: 1,
    label: "启用",
  },
]);
const OrgData = ref<dataSourceType[]>([]);
const selectOption = ref("");
//表格
let scroll: dataSourceType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const configData = reactive({
  records: [],
  total: "",
});
const isShowPagination = ref(true);
const showCheckDelete = true; // 是否需要分页器中的自定义
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
const userSecretIdOptions = ref<SelectProps["options"]>([]);
let rowSelection = ref<(string | number)[]>([]);
// const userSecretId = ref<number>();
const formState = reactive<dataSourceType>({
  userSecretId: null,
});
const tagBaseTables = ref<any>({
  selectedRowKeys: [],
}); //
// 模态框
const modAlProps: dataSourceType = reactive({
  width: "M",
  title: "批量设置密级",
});
const buttons = ref<dataSourceType[]>([
  {
    text: "保存",
    "html-type": "submit",
    keepAlive: true,
  },
]);

const params = ref<any>({
  status: null,
  orgId: null,
  userSecretId: null,
  keyWord: null,
});
const isVisible = ref<Boolean>(false);
// onMounted
onMounted(() => {
  btnPerm.value = routerPerm();
  fetchReinsuranceUserSecretPage({});
  getAllUserSecretList();
  fetchUserOrgTree();
});
watch(
  () => tagBaseTables.value.selectedRowKeys,
  (newVal, oldVal) => {
    rowSelection.value = newVal;
  },
  { deep: true }
);
//methods
// 密级数据
const getAllUserSecretList = async () => {
  const data = (await request.fetchAllUserSecretList({})) || [];
  data.length &&
    data.forEach((item: dataSourceType) => {
      userSecretIdOptions.value?.push({ label: item.name, value: item.id });
      item.value = item.name;
    });
  // sequrityOptions.value = [{ name: "全部", id: 0, value: "全部" }, ...data];
};
//获取当前用户可见组织树
const fetchUserOrgTree = async () => {
  const data = (await request.fetchUserOrgTree()) || [];

  OrgData.value = [
    { name: "全部", id: "" },
    ...data.filter((item: dataSourceType) => !item.authAble),
  ];
};
const changeTopTabs = () => {
  pageCurrent.value = 1;
  pageSize.value = 10;
  fetchReinsuranceUserSecretPage({});
};
// 搜索
const onSearch = () => {
  nextTick(() => {
    fetchReinsuranceUserSecretPage(params.value);
  });
};
// 修改人员密集 失焦触发
const userSecretBlur = (item: any) => {
  let data = {
    secretId: item.userSecretId || null,
    userIds: [item.id] || null,
  };
  request.fetchReinsuranceUserSecretUpdate(data).then((res: dataSourceType) => {
    if ((res.code = "00000 00000")) {
      message.success(res.message);
      fetchReinsuranceUserSecretPage({});
    }
  });
};

const buttonMessage = async (msg: dataSourceType) => {
  let data = {
    secretId: formState.userSecretId,
    userIds: tagBaseTables.value.selectedRowKeys,
  };
  request.fetchReinsuranceUserSecretUpdate(data).then((res: dataSourceType) => {
    if ((res.code = "00000 00000")) {
      message.success(res.message);

      fetchReinsuranceUserSecretPage({});
      isVisible.value = false;
    }
  });
};
// 获取用户密级设置
const fetchReinsuranceUserSecretPage = async (datas: dataSourceType) => {
  tagBaseTables.value.selectedRowKeys = [];
  const data: dataSourceType = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    type: tabActive.value,
    ...params.value,
  };
  selectOption.value ? (data.moduleType = selectOption.value) : "";
  const telData = (await request.fetchReinsuranceUserSecretPage(data)) || {};

  let reqData = telData;
  configData.total = reqData.total;
  configData.records = reqData.records;
  configData.records?.map(
    (item: dataSourceType, index: number) =>
      (item.key = item.id) && (item.index = index + 1)
  );
  nextTick(() => {
    let obj = getTableScroll(74, "secret", 116);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};
//审核列表
const auditRecord = async (record: dataSourceType) => {
  isVisible.value = true;
  formState.userSecretId = null;
};
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  fetchReinsuranceUserSecretPage(datas);
};
</script>
<style lang="less" scoped>
.secret {
  .selectBox {
    margin: 16px 0;

    padding: 8px 0;
    display: flex;
    width: 100%;
    background: rgba(0, 0, 0, 0.02);
    > div {
      margin-right: 24px;
    }
    span {
      width: 120px;
      // margin-right: 16px;
      font-size: 14px;
    }
    .ant-tree-select {
      width: 200px;
    }
  }
  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: left;
    margin-right: 0px;
  }
  :deep(.ant-table-row .ant-table-cell:nth-last-of-type(1)) {
    text-align: left;
    margin-right: 0px;
  }
}
</style>
<style lang="less">
.userSecret {
  width: 200px;
}
.secret {
  .tips {
    margin-bottom: 16px;
  }
  padding: 16px;
  background: #fff;
  height: calc(100% - 120px);

  .options {
    display: flex;
    padding: 24px 0;
    align-items: center;
    font-size: 14px;

    .options_label {
      margin-right: 12px;
    }

    .options_content {
      border: 1px solid var(--theme_button_bg_color, #1f6ded);
      display: flex;
      border-radius: 4px;

      span {
        padding: 4px 14px;
        color: #333;
        border-right: 1px solid var(--theme_button_bg_color, #1f6ded);
      }

      span:nth-last-of-type(1) {
        border-right: none;
      }

      span:hover {
        background: var(--theme_button_hover_bg_color, #4892fa);
        border-color: var(--theme_button_hover_bg_color, #4892fa);
        color: #fff;
      }

      .activeOption {
        color: #fff;
        background: var(--theme_button_bg_color, #1f6ded);
      }
    }
  }

  .eidtRecords {
    margin-right: 12px;
  }

  .ant-table-row {
    .ant-table-cell:nth-last-of-type(1) {
      text-align: right;
    }
  }
}
</style>
